/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package metro.jme.lottery.graphics.screens;

import java.io.IOException;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import metro.jme.lottery.business.Checker;
import metro.jme.lottery.graphics.sprite.ExplosionSprite;
import metro.jme.lottery.graphics.sprite.NumberSprite;
import metro.jme.lottery.main.LotteryMIDlet;
import metro.jme.lottery.util.ImageHelper;

/**
 * Class displaying the result after a check.
 * @author pierre
 */
public class NumberCanvas extends GameCanvas implements Runnable, CommandListener {

	// Main MIDlet
	private LotteryMIDlet m_MIDlet;
	// Command
	private Command m_backCmd;
	private Command m_editCmd;
	// Sprites
	private NumberSprite m_numberSpriteLisa;
	private NumberSprite m_numberSpriteOikeat;
	private ExplosionSprite m_explosionSprite;
	// ...
	private boolean running;
	private int leftCol;
	private int rightCol;
	//Images
	private Image lisa;
	private Image oikeat;
	private boolean lisa_completed = false;
	private boolean oikeat_completed = false;
	private boolean final_completed = false;
	private String gains;
	private String goodResults;
	private String goodBonusResults;
	// Extra
	private boolean big_winner = false;
	// Constant
	private static int ANIMATION_STEP;

	public NumberCanvas(LotteryMIDlet MIDlet) throws Exception {
		super(true);
		// Linking canvas to midlet
		m_MIDlet = MIDlet;

		// Command
		m_backCmd = new Command("Back", Command.BACK, 1);
		m_editCmd = new Command("Edit", Command.ITEM, 1);
		this.addCommand(m_backCmd);
		this.addCommand(m_editCmd);
		
		try {
			init();
		} catch(Exception e) {
			throw e;
		}

	}

	protected final void init() throws Exception {
		// Creating canvas element
		int third = getWidth() / 3;
		leftCol = third;
		rightCol = 2 * third;

		Checker checker;
		try {
			checker = new Checker();
			int good = checker.getGood();
			if (good == 6 || good == 7) {
				big_winner = true;
			}
			int bonus = checker.getBonus();
			gains = "" + checker.getGains();
			goodResults = checker.getResultsAsString();
			goodBonusResults = checker.getBonusResultsAsString();
			if (getWidth() <= ImageHelper.SMALL_DEVICE_TRESHOLD) {
				m_numberSpriteOikeat = NumberSprite.createSprite(leftCol - 60, 50, good, true);
				m_numberSpriteLisa = NumberSprite.createSprite(rightCol - 40, 50, bonus, true);
			} else {
				m_numberSpriteOikeat = NumberSprite.createSprite(leftCol - 60, 50, good, false);
				m_numberSpriteLisa = NumberSprite.createSprite(rightCol - 40, 50, bonus, false);
			}

			int height_third = getHeight() / 3;

			m_explosionSprite = ExplosionSprite.createSprite(getWidth() / 2 - 15, 2 * height_third);
			running = false;

			// Instanciate images
			try {
				// Create images
				lisa = Image.createImage(
						ImageHelper.getOptimalImage("/imgs/lisa.png", getWidth()));
				oikeat = Image.createImage(
						ImageHelper.getOptimalImage("/imgs/oikeat.png", getWidth()));

			} catch (IOException e) {
				e.printStackTrace();
				System.err.println("Error trying to creates images");
			}
		} catch (Exception ex) {
			throw ex;
		}
	}

	/**
	 * 
	 */
	public void start() {
		running = true;
		Thread t = new Thread(this);
		t.start();
	}

	/**
	 * 
	 */
	public void stop() {
		running = false;
	}

	/**
	 * 
	 */
	public void run() {
		displayOikeat();
		displayLisa();
		finalResult();
		running = false;
	}

	/**
	 * Method is called to refresh the content of the canvas
	 * @param g 
	 */
	public void drawDisplay(Graphics g) {
		eraseBackground(g);
		switch (ANIMATION_STEP) {
			case 0:
				m_numberSpriteOikeat.nextFrame();
				m_numberSpriteOikeat.paint(g);
				break;
			case 1:
				m_numberSpriteLisa.nextFrame();
				m_numberSpriteLisa.paint(g);
				break;
			case 2:
				m_explosionSprite.next(g);
				break;
		}
		if (lisa_completed) {
			m_numberSpriteLisa.setFrame(NumberSprite.SEQ_SIZE - 1);
			m_numberSpriteLisa.paint(g);
		}
		if (oikeat_completed) {
			m_numberSpriteOikeat.setFrame(NumberSprite.SEQ_SIZE - 1);
			m_numberSpriteOikeat.paint(g);
		}
		if (final_completed) {
			g.setGrayScale(0);
			Font font = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
			g.setFont(font);
			int height_third = getHeight() / 3;
			g.drawString(gains + "€", getWidth() / 2 - 10, 2 * height_third + 10, Graphics.TOP | Graphics.LEFT);
			font = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_UNDERLINED, Font.SIZE_SMALL);
			g.setFont(font);
			g.drawString(goodResults, 5, 2 * height_third + 30, Graphics.TOP | Graphics.LEFT);
			g.drawString("Bonus:" + goodBonusResults, 5, 2 * height_third + 45, Graphics.TOP | Graphics.LEFT);
		}
		g.drawImage(oikeat, leftCol - (oikeat.getWidth() / 2), 20, Graphics.TOP | Graphics.LEFT);
		g.drawImage(lisa, rightCol - (lisa.getWidth() / 2), 20, Graphics.TOP | Graphics.LEFT);
		flushGraphics();
	}

	/**
	 * 
	 * @param g 
	 */
	public void eraseBackground(Graphics g) {
		g.setColor(0x0000ff);
		g.setGrayScale(255);
		g.fillRect(0, 0, getWidth(), getHeight());
	}

	/**
	 * 
	 */
	private void displayOikeat() {
		ANIMATION_STEP = 0;
		Graphics g = getGraphics();
		int delay = 10;
		while (m_numberSpriteOikeat.next() && running) {
			try {
				drawDisplay(g);
				Thread.sleep(delay);
				delay += 10;
			} catch (InterruptedException ex) {
				System.err.println("Thread exception");
				ex.printStackTrace();
			}
		}
		System.out.println("Oikeat done");
		oikeat_completed = true;
	}

	/**
	 * 
	 */
	private void displayLisa() {
		ANIMATION_STEP = 1;
		Graphics g = getGraphics();
		int delay = 10;
		while (m_numberSpriteLisa.next() && running) {
			try {
				drawDisplay(g);
				Thread.sleep(delay);
				delay += 10;
			} catch (InterruptedException ex) {
				System.err.println("Thread exception");
				ex.printStackTrace();
			}
		}
		System.out.println("Lisa done");
		lisa_completed = true;
	}

	/**
	 * 
	 */
	private void finalResult() {
		ANIMATION_STEP = 2;
		Graphics g = getGraphics();
		int delay = 50;
		if (big_winner) {
			m_MIDlet.pauseSong();
			m_MIDlet.play("jingle");
		}
		while (!m_explosionSprite.done() && running) {
			try {
				drawDisplay(g);
				Thread.sleep(delay);
			} catch (InterruptedException ex) {
				System.err.println("Thread exception");
				ex.printStackTrace();
			}
		}
		// Last display : 
		final_completed = true;
		drawDisplay(g);
	}

	/**
	 * 
	 * @param cmnd
	 * @param dsplbl 
	 */
	public void commandAction(Command cmnd, Displayable dsplbl) {
		// First stop the current thread
		this.stop();
		if (cmnd == m_backCmd) {
			back();
		} else if (cmnd == m_editCmd) {
			EditURLForm euf = new EditURLForm(m_MIDlet, this);
			euf.setCommandListener(euf);
			m_MIDlet.displayNewScreen(euf);
		}
	}

	/**
	 * 
	 */
	private void back() {
		m_MIDlet.back();
	}

	public boolean isRunning() {
		return running;
	}
}
